// ==UserScript==
// @namespace librecitizen
// @version 1.1
// @description Replacements for all JavaScript of the websites for Executive, Judiciary and Legislative government powers. Configure your browser to **disable** all JavaScript.
// @description:pt-BR Substitutos a todo o JavaScript dos sites dos poderes Executivo, Judiciário e Legislativo. Configure teu navegador para **desativar** todo o JavaScript.

// @name LibreCitizen: Brazil Senado Federal's e-Cidadania
// @name:pt-BR LibreCitizen: e-Cidadania do Senado Federal do Brasil
// @match *://www12.senado.leg.br/ecidadania*
// @grant none
// @require https://git.savannah.nongnu.org/cgit/userjs-common.git/plain/userjs-common.js?h=1.5
// ==/UserScript==

/*
@source https://notabug.org/adfeno/librecitizen/archive/1.1.tar.gz

@licstart The following is the entire license notice for the
JavaScript code in this page.

LibreCitizen: Replacements for all JavaScript of the websites for 
Executive, Judiciary and Legislative government powers.
Copyright (C) 2019, 2021, 2024  Adonay Felipe Nogueira <https://libreplanet.org/wiki/User:Adfeno> <adfeno.7046@gmail.com>

This file is part of LibreCitizen.

LibreCitizen is free software: you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the 
Free Software Foundation, either version 3 of the License, or (at your 
option) any later version.

LibreCitizen is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
General Public License for more details.

You should have received a copy of the GNU Affero General Public License 
along with LibreCitizen.  If not, see <https://www.gnu.org/licenses/>.

As additional permission under GNU GPL version 3 section 7, you may 
distribute non-source (e.g., minimized or compacted) forms of that code 
without the copy of the GNU GPL normally required by section 4, provided 
you include this license notice and a URL through which recipients can 
access the Corresponding Source.

@licend The above is the entire license notice for the JavaScript code 
in this page.

# Contact and contributing

See <https://notabug.org/adfeno/librecitizen>.

# Dependencies

## Common Userscript Definitions (userjs-common)

Version: 1.5
License: GPL-3.0-or-later

Reference: https://git.savannah.nongnu.org/cgit/userjs-common.git/tag/?h=1.5

There is no need to manually get this dependency since part of it will be 
downloaded through the @require property of this userscript's metadata 
block when installing it.
*/

style_class_name = "librecitizen";

document.head.appendChild(document.createElement("style")).innerText = `
#portal-login,
details > * {
  display: initial !important;
}

.collapse {
  border: initial !important;
  border-radius: initial !important;
  padding: initial !important;
}
`;

window.onerror = alert;

function set_csrf_protection_cookie() {
  /*
  Sets cookie for the cross-site request forgery (CSRF) protection token.
  */

  if (get_cookie("X-CSRF-TOKEN")) {
    return true;
  } else if (! document.querySelector('#protect-script')) {
    return false;
  }

  document.cookie = "X-CSRF-TOKEN=" +
    encodeURIComponent(document.querySelector('#protect-script')
      .getAttribute("data-token")) +
    ";" +
    "domain=" + document.location.host + ";" +
    "path=/ecidadania;" +
    "samesite=strict";

  return true;
}

function make_details_and_summary(selector_string) {
  document.querySelectorAll(selector_string).forEach(
    function replace_with_summary_and_details(anchor_element) {
      var old_detail_element =
        document.querySelector((new URL(anchor_element.href)).hash);

      var new_detail_element =
        clone_element_remvoing_event_handlers_and_listeners(
          old_detail_element,
          true
        );

      var details = new Map(
        [
          [
            "root",
            document.createDocumentFragment(),
          ],
          [
            "details",
            new Map(
              [
                [
                  "root",
                  document.createElement("details"),
                ],
                [
                  "summary",
                  new Map(
                    [
                      [
                        "root",
                        document.createElement("summary"),
                      ],
                      [
                        "title",
                        document.createElement("h2"),
                      ],
                    ]
                  ),
                ],
              ]
            ),
          ],
        ]
      );

      details.get("details").get("summary").get("title").innerText =
        anchor_element.innerText;

      details.get("details").set(
        "content",
        new_detail_element
      );

      append_map_entries_to_root_node(details);
      old_detail_element.parentNode.replaceChild(
        details.get("root"),
        old_detail_element
      );

      remove_element(anchor_element);
    }
  );
}

async function get_comments_and_warnings() {
  var request = new Request(
    document.location.origin +
      "/ecidadania/ajaxcolecaocomentarioaudiencia" +
      "?" +
      "audienciaId=" +
      (new URLSearchParams(document.location.search)).get("id")
  );

  var response = await fetch(request);
  if (response.status == 200) {
    response = await response.text();
    var template = document.createElement("template");

    template.innerHTML = response;
    document.querySelector('#comentarios').appendChild(template.content);
  } else {
    console.debug(
      request,
      response,
      await response.text()
    );
    throw new Error(common_messages.error_unhandled_response_status);
  }

  var request = new Request(
    document.location.origin +
      "/ecidadania/ajaxmensagemavisoaudiencia" +
      "?" +
      "audienciaId=" +
      (new URLSearchParams(document.location.search)).get("id")
  );

  response = await fetch(request);
  if (response.status == 200) {
    response = await response.text();
    var template = document.createElement("template");

    template.innerHTML = response;
    document.querySelector('#box-aviso').appendChild(template.content);
  } else {
    console.debug(
      request,
      response,
      await response.text()
    );
    throw new Error(common_messages.error_unhandled_response_status);
  }
}

(async function keep_authenticated() {
  if (! set_csrf_protection_cookie()) {
    return false;
  }

  var request = new Request(
    document.location.origin +
      "/ecidadania/ajaxportaluser",
    {
      "method": "POST",
    }
  );

  var response = await fetch(request);
  if (response.status == 200) {
    // name: nome; login: e-mail
    response = await response.json();

    document.querySelector('#portal-login ins').innerText =
      response.name.toLowerCase();

    if (! localStorage.getItem("logged")) {
      localStorage.setItem("logged", "1");
    }
  } else {
    console.debug(
      request,
      response,
      await response.text()
    );
    throw new Error(common_messages.error_unhandled_response_status);
  }

  if (
      /^\/ecidadania\/visualizacaoaudiencia$/.test(document.location.pathname)
    ) {

    request = new Request(
      document.location.origin +
        "/ecidadania/ajaxautenticacaoaudiencia",
      {
        "method": "POST",
        "body": {
          "audienciaId": document.querySelector('#audienciaId').value,
          "_authenticator": document.querySelector('#_authenticator').value,
        },
      }
    );

    response = await fetch(request);
    if (response.status != 200) {
      console.debug(
        request,
        response,
        await response.text()
      );
      throw new Error(common_messages.error_unhandled_response_status);
    }
  }
})();

if (get_cookie("X-CSRF-TOKEN")) {
  for (let each_form of document.getElementsByTagName("FORM")) {
      var fragment_with_authentication_input =
        document.createDocumentFragment();
      var authentication_input = document.createElement("input");

      authentication_input.type = "hidden";
      authentication_input.name = "_authenticator";
      authentication_input.value = get_cookie("X-CSRF-TOKEN");

      fragment_with_authentication_input.appendChild(authentication_input);
      each_form.appendChild(fragment_with_authentication_input);
  }
}

if (/^\/ecidadania\/login(?:_form)?$/.test(document.location.pathname)) {
  var old_login_form = document.querySelector('#login_form');
  var new_login_form = clone_element_remvoing_event_handlers_and_listeners(
    old_login_form,
    true
  );

  document.querySelectorAll('.login-termo')
    .forEach(function add_term_to_login_form(old_term_element) {
      var new_term_element =
        clone_element_remvoing_event_handlers_and_listeners(
          old_term_element,
          true
        );

      new_term_element.querySelectorAll('input[type="checkbox"]')
        .forEach(function make_checkbox_required(input_checkbox) {
          input_checkbox.required = true;
        });

      new_login_form.querySelector('.formControls').parentNode.insertBefore(
        new_term_element,
        new_login_form.querySelector('.formControls')
      );

      remove_element(old_term_element);
    });

  old_login_form.parentNode.replaceChild(
    new_login_form,
    old_login_form
  );
} else if (/^\/ecidadania\/logged_out$/.test(document.location.pathname)) {
  document.cookie = "X-CSRF-TOKEN=;" +
    "domain=" +
    document.location.host +
    ";" +
    "expires=" +
    (new Date(Date.now() - 1 * 1000)).toUTCString() +
    ";" +
    "path=/ecidadania;" +
    "samesite=strict";
  localStorage.removeItem("logged");
} else if (
    /^\/ecidadania\/visualizacaoaudiencia$/
      .test(document.location.pathname)
  ) {

  get_comments_and_warnings();

  document.querySelectorAll('#div-comentarios form')
    .forEach(function replace_comment_form(old_comment_form) {
      new_comment_form = clone_element_remvoing_event_handlers_and_listeners(
        old_comment_form,
        true
      );

      new_comment_form.method = "post";
      new_comment_form.action = "ajaxcomentarioaudiencia";

      new_comment_form.querySelector('#comentario').name =
        new_comment_form.querySelector('#comentario').id;
      new_comment_form.querySelector('#comentario').setAttribute(
        "maxlength",
        140
      );

      new_comment_form.querySelector('#btn-enviar').type = "submit";

      var audience_identity_hidden_input = document.createElement("input");
      audience_identity_hidden_input.type = "hidden";
      audience_identity_hidden_input.name = "audienciaId";
      audience_identity_hidden_input.value =
        (new URLSearchParams(document.location.search)).get("id");
      new_comment_form.appendChild(audience_identity_hidden_input);

      old_comment_form.parentNode.replaceChild(
        new_comment_form,
        old_comment_form
      );
    });

  document.querySelectorAll('.link-declaracao-participacao')
    .forEach(function replace_declaration_element(old_declaration_element) {
      new_declaration_element = new Map(
        [
          [
            "root",
            document.createDocumentFragment(),
          ],
          [
            "form",
            new Map(
              [
                [
                  "root",
                  document.createElement("form"),
                ],
                [
                  "audience_identity",
                  document.createElement("input"),
                ],
                [
                  "submit_input",
                  document.createElement("input"),
                ],
              ]
            ),
          ],
        ]
      );

      new_declaration_element.get("form").get("root").action =
        "declaracaoparticipacaoaudiencia";

      new_declaration_element.get("form").get("audience_identity").name =
        "audienciaId";
      new_declaration_element.get("form").get("audience_identity").type =
        "hidden";
      new_declaration_element.get("form").get("audience_identity").value =
        (new URLSearchParams(document.location.search)).get("id");

      new_declaration_element.get("form").get("submit_input").type =
        "submit";
      new_declaration_element.get("form").get("submit_input").value =
        old_declaration_element.innerText;
      if (
          ! localStorage.getItem("logged") ||
          (
            localStorage.getItem("logged") &&
            document.querySelector('#situacaoId:not([value="4"])')
          )
        ) {

        new_declaration_element.get("form").get("submit_input").disabled =
          true;
      }

      append_map_entries_to_root_node(new_declaration_element);
      old_declaration_element.parentNode.replaceChild(
        new_declaration_element.get("root"),
        old_declaration_element
      );
    });

  make_details_and_summary('#audiencia a.collapsed');
} else if (
    /^\/ecidadania\/visualizacaoideia$/
      .test(document.location.pathname)
  ) {

  document.querySelectorAll('#barra-voto > .btn.ideia-btn-apoio')
    .forEach(function replace_unstandardized_support_button(old_button) {
      var new_button = new Map(
        [
          [
            "root",
            document.createDocumentFragment(),
          ],
          [
            "form",
            new Map(
              [
                [
                  "root",
                  document.createElement("form"),
                ],
                [
                  "authenticator",
                  document.querySelector('[name="_authenticator"]'),
                ],
                [
                  "idea_identity",
                  document.createElement("input"),
                ],
                [
                  "submit_input",
                  document.createElement("input"),
                ],
              ]
            ),
          ],
        ]
      );

      if (! new_button.get("form").get("authenticator")) {
        throw new Error("Não autenticado!");
      }

      new_button.get("form").set(
        "authenticator",
        new_button.get("form").get("authenticator").cloneNode(true)
      );

      new_button.get("form").get("root").method = "post";
      new_button.get("form").get("root").action =
        "ajaxapoiamentoideia";

      new_button.get("form").get("idea_identity").name =
        "id";
      new_button.get("form").get("idea_identity").type =
        "hidden";
      new_button.get("form").get("idea_identity").value =
        (new URLSearchParams(document.location.search)).get("id");

      new_button.get("form").get("submit_input").type =
        "submit";
      new_button.get("form").get("submit_input").value =
        old_button.innerText;

      append_map_entries_to_root_node(new_button);
      old_button.parentNode.replaceChild(
        new_button.get("root"),
        old_button
      );
    });

  make_details_and_summary('#ideia-legislativa a.collapsed');
} else if (
    /^\/ecidadania\/visualizacaomateria$/
      .test(document.location.pathname)
  ) {

  var old_form;
  if (old_form = document.querySelector('#barra-voto')) {
    var new_form = new Map(
      [
        [
          "root",
          document.createDocumentFragment(),
        ],
        [
          "form",
          new Map(
            [
              [
                "root",
                document.createElement("form"),
              ],
              [
                "authenticator",
                document.querySelector('[name="_authenticator"]'),
              ],
              [
                "subject_identity",
                document.createElement("input"),
              ],
            ]
          ),
        ],
      ]
    );

    if (! new_form.get("form").get("authenticator")) {
      throw new Error("Not authenticated!");
    }

    new_form.get("form").set(
      "authenticator",
      new_form.get("form").get("authenticator").cloneNode(true)
    );

    new_form.get("form").get("root").method = "post";
    new_form.get("form").get("root").action = "ajaxapoiamentomateria";

    new_form.get("form").get("subject_identity").name = "materiaId";
    new_form.get("form").get("subject_identity").type = "hidden";
    new_form.get("form").get("subject_identity").value =
      (new URLSearchParams(document.location.search)).get("id");

    old_form.querySelectorAll('.btn[data-voto]')
      .forEach(function get_old_vote_button(old_button) {
        new_form.get("form").set(
          old_button.getAttribute("data-voto"),
          document.createElement("input")
        );
        new_form.get("form").set(
          old_button.getAttribute("data-voto") +
            "_label",
          document.createElement("label")
        );

        new_form.get("form").get(old_button.getAttribute("data-voto")).id =
          old_button.getAttribute("data-voto");
        new_form.get("form").get(old_button.getAttribute("data-voto")).name =
          "voto";
        new_form.get("form").get(old_button.getAttribute("data-voto")).type =
          "radio";
        new_form.get("form").get(old_button.getAttribute("data-voto")).value =
          old_button.getAttribute("data-voto");

        new_form.get("form").get(
          old_button.getAttribute("data-voto") +
            "_label"
        ).setAttribute(
          "for",
          old_button.getAttribute("data-voto")
        );
        new_form.get("form").get(
          old_button.getAttribute("data-voto") +
            "_label"
        ).innerText = old_button.innerText;
      });

    new_form.get("form").set(
      "submit_input",
      document.createElement("input")
    );
    new_form.get("form").get("submit_input").type = "submit";
    new_form.get("form").get("submit_input").value = common_messages.submit;

    append_map_entries_to_root_node(new_form);
    old_form.parentNode.replaceChild(
      new_form.get("root"),
      old_form
    );
  }

  make_details_and_summary(
    '#materia-legislativa a[data-toggle="collapse"], ' +
      '.materia-ementaExplicacao a[data-toggle="collapse"]'
  );
}
